import 'dart:collection';

import 'package:dio/dio.dart';
import 'package:dk_flutter_base/dk_core.dart';

///网络请求的默认拦截器，蛋壳网络拦截器基本一致，所以通常都是用默认拦截器
class DefaultRequestInterceptor extends Interceptor {
  static const String REQUEST_SUCCESS_CODE = "0000";
  static const String HTTP_METHOD_GET = "GET";
  static const String HTTP_METHOD_POST = "POST";
  static const String HTTP_METHOD_PUT = "PUT";
  static const String HTTP_METHOD_DELETE = "DELETE";

  @override
  onRequest(RequestOptions options) async {
    Map<String, dynamic> paramsMap;
    String verifyData;
    switch (options.method) {
      case HTTP_METHOD_GET:
      case HTTP_METHOD_DELETE:
        if (null == options.queryParameters) {
          options.queryParameters = Map<String, dynamic>();
        }
        options.queryParameters = SplayTreeMap.of(options.queryParameters);
        paramsMap = options.queryParameters;
        CommonSignUtil.addTimeStampForMap(paramsMap);
        verifyData = CommonSignUtil.addUrlMd5ForMap(paramsMap);
        break;
      case HTTP_METHOD_POST:
      case HTTP_METHOD_PUT:
        if (null == options.data) {
          options.data = Map<String, dynamic>();
        }
        paramsMap = options.data;
        CommonSignUtil.addTimeStampForMap(paramsMap);
        verifyData = CommonSignUtil.addBodyMd5ForMap(paramsMap);
        break;
    }
    var map = await CommonSignUtil.getCommonHeaders(verifyData);
    options.headers.addAll(map);
  }

  @override
  onError(DioError err) {}

  @override
  onResponse(Response response) {}
}
